package cn.frontop.funswitch.controller;

import cn.frontop.funswitch.common.Result;
import cn.frontop.funswitch.entity.ApiPathEntity;
import cn.frontop.funswitch.entity.IndexConfigEntity;
import cn.frontop.funswitch.param.JsonPathParam;
import cn.frontop.funswitch.service.ApiPathService;
import cn.frontop.funswitch.service.IndexConfigService;
import cn.frontop.funswitch.util.CommonUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jayway.jsonpath.JsonPath;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.stream.Collectors;


/**
 * 请求路径
 *
 * @author Yun
 * @email Yun@frontop.cn
 * @date 2022-10-19 15:41:15
 */
@RestController
@RequestMapping("apiPath")
@Api(tags = "API接口管理")
public class ApiPathController {
    @Autowired
    private ApiPathService apiPathService;
    @Autowired
    private IndexConfigService indexConfigService;

    /**
     * 查看API接口列表
     *
     * @param pageNo   当前页码
     * @param pageSize 每页显示条数
     * @return 结果集
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation("查看API接口列表")
    public Result<?> queryApiPathList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                      @RequestParam(name = "projectId", defaultValue = "1") Integer projectId) {
        return CommonUtil.entityPageList(apiPathService, pageNo, pageSize, new QueryWrapper<ApiPathEntity>().lambda().eq(ApiPathEntity::getProjectId, projectId).orderByDesc(ApiPathEntity::getCreatedTime), o -> {
            JSONArray objects = JSONUtil.parseArray(o);
            return objects.stream().map(t -> JSONUtil.toBean(JSONUtil.parseObj(t), ApiPathEntity.class)).peek(t -> {
                IndexConfigEntity byId = indexConfigService.getById(t.getIndexId());
                if (byId != null && 3 != t.getType()) {
                    t.setIndexName(byId.getName());
                }
            }).collect(Collectors.toList());
        });

    }

    /**
     * 模糊查询API接口列表
     *
     * @param pageNo   当前页码
     * @param pageSize 每页显示条数
     * @return 结果集
     */
    @RequestMapping(value = "/fuzzyQuery", method = RequestMethod.GET)
    @ApiOperation("模糊查询API接口列表")
    public Result<?> fuzzyQuery(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam(name = "projectId", defaultValue = "1") Integer projectId, @RequestParam(name = "name") String name) {
        return CommonUtil.entityPageList(apiPathService, pageNo, pageSize, new QueryWrapper<ApiPathEntity>().lambda().eq(ApiPathEntity::getProjectId, projectId).like(ApiPathEntity::getApiPath, name).or().eq(ApiPathEntity::getProjectId, projectId).like(ApiPathEntity::getName, name).orderByDesc(ApiPathEntity::getCreatedTime), o -> {
            JSONArray objects = JSONUtil.parseArray(o);
            return objects.stream().map(t -> JSONUtil.toBean(JSONUtil.parseObj(t), ApiPathEntity.class)).peek(t -> {
                IndexConfigEntity byId = indexConfigService.getById(t.getIndexId());
                if (byId != null && 3 != t.getType()) {
                    t.setIndexName(byId.getName());
                }
            }).collect(Collectors.toList());
        });

    }

    /**
     * 查看API接口列表
     *
     * @return 结果集
     */
    @RequestMapping(value = "/callBackList", method = RequestMethod.GET)
    @ApiOperation("查询回调接口")
    public Result<?> queryCallBackList() {
        return Result.ok(apiPathService.getBaseMapper().selectList(new QueryWrapper<ApiPathEntity>().lambda().eq(ApiPathEntity::getType, 5).eq(ApiPathEntity::isStatus, true)));
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("查询API信息")
    public Result<ApiPathEntity> info(@PathVariable("id") Integer id) {
        ApiPathEntity apiPath = apiPathService.getById(id);
        return Result.ok(apiPath);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("保存API")
    public Result<String> save(@RequestBody ApiPathEntity apiPath) {
        apiPathService.save(apiPath);
        return Result.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("修改API")
    public Result<String> update(@RequestBody ApiPathEntity apiPath) {
        apiPath.setUpdatedTime(new Date());
        apiPathService.updateById(apiPath);
        return Result.ok();
    }

    /**
     * 删除
     */
    @GetMapping("/delete/{id}")
    @ApiOperation("删除API")
    public Result<String> delete(@PathVariable("id") Integer id) {
        apiPathService.removeById(id);
        return Result.ok();
    }

    /**
     * 上线
     */
    @GetMapping("/online/{id}")
    @ApiOperation("上线")
    public Result<String> online(@PathVariable("id") Integer id, HttpServletRequest request) {
        ApiPathEntity apiPathEntity = apiPathService.getById(id);
        apiPathEntity.setStatus(true);
        switch (apiPathEntity.getType()) {
            case 0:
                apiPathEntity.setDocument(StrUtil.isNotEmpty(indexConfigService.getById(JSONUtil.isTypeJSONArray(apiPathEntity.getIndexId()) ? JSONUtil.parseArray(apiPathEntity.getIndexId()).getInt(0) : apiPathEntity.getIndexId()).getParam()) ? null : JSONUtil.toJsonStr(CommonUtil.process(apiPathEntity, request, indexConfigService).getResult()));
                break;
            case 3:
            case 6:
                apiPathEntity.setDocument(JSONUtil.toJsonStr(CommonUtil.process(apiPathEntity, request, indexConfigService).getResult()));
                break;
            default:
                apiPathEntity.setDocument(null);
                break;
        }
        apiPathService.updateById(apiPathEntity);
        return Result.ok();
    }

    /**
     * 下线
     */
    @GetMapping("/offline/{id}")
    @ApiOperation("下线")
    public Result<String> offline(@PathVariable("id") Integer id) {
        ApiPathEntity apiPathEntity = apiPathService.getById(id);
        apiPathEntity.setStatus(false);
        apiPathService.updateById(apiPathEntity);
        return Result.ok();
    }

    /**
     * jsonPath
     */
    @PostMapping("/jsonPath")
    @ApiOperation("jsonPath")
    public Result<String> jsonPath(@RequestBody JsonPathParam jsonPathParam) {
        return Result.ok(JsonPath.read(jsonPathParam.getData(), jsonPathParam.getJsonPath()).toString());
    }
}
